//
//  WYComposePictureView.swift
//  WYWeibo
//
//  Created by wangyi on 16/7/24.
//  Copyright © 2016年 wangyi. All rights reserved.
//

import UIKit

//重用标记
private let WYomPosePictureViewCellIndentifier = "WYomPosePictureViewCellIndentifier"
//发微博页面的配图
class WYComposePictureView: UICollectionView {

    //储存添加的图片
    lazy var images = [UIImage]()
    
    //点击按钮的执行闭包
    var didSelectedAddClouse: (() -> ())?
    
    override init(frame: CGRect, collectionViewLayout layout: UICollectionViewLayout) {
        let flowLayout = UICollectionViewFlowLayout()
        super.init(frame: frame, collectionViewLayout: flowLayout)
        setUPUI()
    }

    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    //添加控件
    private func setUPUI() {
    
        backgroundColor = RandomColor()
        //默认 隐藏配图
        hidden = false
        //设置代理
        delegate = self
        //设置数据源
        dataSource = self
        //注册 cell
        registerClass(WYComposePictureViewCell.self, forCellWithReuseIdentifier: WYomPosePictureViewCellIndentifier)
    }
    func addImage(image: UIImage) {
        //显示配图 
        hidden = false
        //添加照片
        images.append(image)
        //重新加载界面
        reloadData()
    }
    //自动布局 这个是添加到父控件上的位置
    override func layoutSubviews() {
        super.layoutSubviews()
        //间距
        let itemMargin: CGFloat = 5
        //每项大小
        let itemWidth = (width - 2 * itemMargin) / 3
        //获取布局方式
        let flowLayout = self.collectionViewLayout as! UICollectionViewFlowLayout
        flowLayout.itemSize = CGSize(width: itemWidth, height: itemWidth)
        //设置水平间距
        flowLayout.minimumInteritemSpacing = itemMargin
        flowLayout.minimumLineSpacing = itemMargin
    }
}

extension WYComposePictureView: UICollectionViewDataSource, UICollectionViewDelegate {
    
    func collectionView(collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
//        return images.count
        //如果是 0 或者 9 张图片原始数据不用添加一张加好图片
        if images.count == 9 || images.count == 0 {
        
            return images.count
        } else {
        
            return images.count + 1
        }
    }
    func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell {
        let cell = collectionView.dequeueReusableCellWithReuseIdentifier(WYomPosePictureViewCellIndentifier, forIndexPath: indexPath) as! WYComposePictureViewCell
//        cell.backgroundColor = RandomColor()
        cell.backgroundColor = UIColor.whiteColor()
        if indexPath.item == images.count {
        
            //设置加好按钮
            cell.image = nil
        } else {
            //设置模型
            cell.image = images[indexPath.item]
        }
        
       // 设置闭包 
        cell.deletebuttonClouse = {
            //点击对应的土片删除
            self.images.removeAtIndex(indexPath.item)
            //判断 如果数据源没有数据 则隐藏
            if self.images.count == 0 {
            
                self.hidden = true
            }
            self.reloadData()
        }
        return cell
    }
    
    func collectionView(collectionView: UICollectionView, didSelectItemAtIndexPath indexPath: NSIndexPath) {
        //表示添加按钮
        if indexPath.item == images.count {
            
            //选择支持高亮图片
            collectionView.deselectItemAtIndexPath(indexPath, animated: true)
            //执行闭包
            didSelectedAddClouse?()
        }
    }
    
}

//配图 cell
class WYComposePictureViewCell: UICollectionViewCell {
    
    //设置闭包
    var deletebuttonClouse: (()-> ())?
    
    var image: UIImage? {
    
        didSet {
        
            if image == nil {
                
                imageView.image = UIImage(named: "compose_pic_add")
                deleteButton.hidden = true
                //设置高亮图片
                imageView.image = UIImage(named: "compose_pic_add_highlighted")
            } else {
                //设置选中的图片
                imageView.image = image
                //显示闪删除按钮
                deleteButton.hidden  = false
                //取消高亮效果
                imageView.highlighted = true
            }
        }
    }
    //懒加载控件
    private lazy var imageView: UIImageView = UIImageView(image: UIImage(named: "timeline_image_placeholder"))
    
    //删除按钮
    private lazy var deleteButton: UIButton = {
    
        let button = UIButton()
        button.setImage(UIImage(named: "compose_photo_close"), forState: .Normal)
        button.addTarget(self, action: "deleteButtonAction", forControlEvents: .TouchUpInside)
        
        return button
    }()
    //懒加载
    override init(frame: CGRect) {
        super.init(frame: frame)
        setUpUI()
    }

    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    private func setUpUI() {
        //添加控件
        contentView.addSubview(imageView)
        contentView.addSubview(deleteButton)
        //设置坐标
        imageView.snp_makeConstraints { (make) -> Void in
            make.edges.equalTo(contentView).offset(UIEdgeInsetsZero)
        }
        deleteButton.snp_makeConstraints { (make) -> Void in
            make.top.equalTo(imageView)
            make.trailing.equalTo(imageView)
        }
    }
    
    //删除按钮的点击事件
    @objc private func deleteButtonAction() {
    
        deletebuttonClouse?()
    }
    
}